//
// Created by qiangqiangj on 2019/10/30.
//
#include "url.h"
#include "request.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>

#define BUFFSIZE 4096
#define TEXT_BUFFSIZE 1024

char *get(const char *urls) {
    struct URL *url = url_parse(urls);
    char *host = url->host;
    int port = url->port;
    char *path = url->path;
    char request[BUFFSIZE], text[BUFFSIZE];
    int socketid, connectid, res, flag = 1;
    struct hostent *purl = NULL;
    struct sockaddr_in sockinfo;

    socketid = socket(AF_INET, SOCK_STREAM, 0);
    if (socketid == -1) {
        printf("创建socket连接失败\n");
        exit(1);
    }

    // 返回值 ：成功返回hostent结构指针，失败则返回NULL指针
    purl = gethostbyname(host);

    // 设置连接信息结构
    memset(&sockinfo, 0, sizeof(struct sockaddr_in));
    sockinfo.sin_family = AF_INET;
    sockinfo.sin_addr.s_addr = *((unsigned long *) purl->h_addr_list[0]);
    sockinfo.sin_port = htons(port);

    // 构造http请求
    memset(request, 0, BUFFSIZE);
    strcat(request, "GET /");
    strcat(request, path);
    strcat(request, " HTTP/1.1\r\n");
    // 以上为http请求行信息
    strcat(request, "HOST: ");
    strcat(request, host);
    strcat(request, "\r\n");
    strcat(request, "User-Agent: http-ci\r\n");
    strcat(request, "Content-Type: text/plain\r\n");
    strcat(request, "Connection: close\r\n");
    strcat(request, "\r\n");

    // 连接到远端服务器
    connectid = connect(socketid, (struct sockaddr *) &sockinfo, sizeof(sockinfo));
    if (connectid == -1) {
        printf("连接远端服务器失败\n");
        exit(1);
    }

    // 向服务器发送GET请求
    res = write(socketid, request, strlen(request));
    if (res == -1) {
        printf("向服务器发送GET请求失败\n");
        exit(1);
    }

    // 接受服务器的响应
    while (flag) {
        memset(text, 0, TEXT_BUFFSIZE);
        int bufflen = recv(socketid, text, TEXT_BUFFSIZE, 0);
        if (bufflen < 0) {
            printf("接收数据流出错\n");
            fclose(stdout);
            close(socketid);
            exit(1);
        }

        if (bufflen > 0) {
            printf("%s", text);
        } else {
            flag = 0;
        }
    }
    fclose(stdout);
    close(socketid);
    return 0;
}